<template>
  <div class="cylinderFlowControl-TabReceive">
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="csmType" style="width: 170px; margin-right: 2px;">
          <el-option label="领瓶人" value="operator" />
          <el-option label="确认人" value="auditor" />
        </el-select>
        <el-input v-model="csmText" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="领瓶出库仓库" prop="outStoreId">
        <el-select v-model="query.outStoreId" placeholder="请选择" clearable>
          <el-option
            v-for="item in storeList"
            :key="item.storeId"
            :label="item.storeName"
            :value="item.storeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="领瓶入库仓库" prop="inStoreId">
        <el-select v-model="query.inStoreId" placeholder="请选择" clearable>
          <el-option
            v-for="item in storeList"
            :key="item.storeId"
            :label="item.storeName"
            :value="item.storeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
          <el-option label="领瓶时间" value="operatorTime" />
          <el-option label="确认时间" value="auditTime" />
        </el-select>
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="query.billStatus" clearable placeholder="请选择">
          <el-option
            v-for="item in bottleStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <span>领瓶数量总计:{{ receiveSum }}</span>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />

    <DetailDialog ref="DetailDialogRef" />
  </div>
</template>

<script>
  import {
    queryReceiveBottleList,
    queryMap,
    queryStoreListByReType,
    receiveBottleAudit,
    receiveBottleInvalid
  } from '@/api'
  import moment from 'dayjs'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { formatColumnMap, parseTime } from '@/utils'
  import DetailDialog from './components/DetailDialog'
  export default {
    name: 'tab-receive',
    components: {
      DetailDialog
    },
    data() {
      return {
        actionColWidth: 80,
        bottleStatusMap: [],
        storeList: [],
        csmType: 'operator',
        csmText: '',
        dateType: 'operatorTime',
        date: [new Date(), new Date()],
        query: {
          outStoreId: '',
          inStoreId: '',
          billStatus: ''
        },
        tableData: {
          total: 0,
          data: []
        },
        receiveSum: 0
      }
    },
    computed: {
      column: function() {
        return [
          {
            prop: 'invenBillCode',
            label: '单号',
            width: 110
          },
          {
            prop: 'operator',
            label: '领瓶人'
          },
          {
            prop: 'operatorTime',
            label: '领瓶时间',
            render: (h, { row }) => (
            <span>
              {row.operatorTime && parseTime(row.operatorTime, '{y}-{m}-{d} {h}:{i}:{s}')}
            </span>
          )
          },
          {
            label: '仓库(出->入)',
            width: 110,
            render: (h, { row }) => {
              if (row.outStoreName && row.inStoreName) {
                return <span>{row.outStoreName + '->' + row.inStoreName}</span>
              }
              return ''
            }
          },
          {
            prop: 'count',
            align: 'right',
            label: '领瓶数量',
            render: (h, { row }) => {
              return (
              <el-link size='mini' underline={false} onClick={() => this.detali(row)}>
                {row.count}
              </el-link>
              )
            }
          },
          {
            prop: 'auditor',
            label: '确认人'
          },
          {
            prop: 'auditTime',
            label: '确认时间',
            render: (h, { row }) => (
            <span>
              {row.auditTime && parseTime(row.auditTime, '{y}-{m}-{d} {h}:{i}:{s}')}
            </span>
          )
          },
          {
            prop: 'billStatus',
            label: '状态',
            render: (h, { row }) => (
            <span>
              {row.billStatus &&
                formatColumnMap(this.bottleStatusMap, 'value', row.billStatus, 'desc')}
            </span>
          )
          },
          {
            label: '操作',
            align: 'center',
            fixed: 'right',
            className: 'action-col',
            width: this.actionColWidth,
            render: (h, { row, $index }) => {
              return (
              <div>
                {row.billStatus === 1 && (
                  <el-link size='mini' onClick={() => this.confirm(row, $index)}>
                    确认
                  </el-link>
                )}
                {row.billStatus === 1 && (
                  <el-link
                    size='mini'
                    type='danger'
                    onClick={() => this.invalid(row, $index)}
                  >
                    作废
                  </el-link>
                )}
              </div>
              )
            }
          }
        ]
      }
    },
    mounted() {
      this.getStoreList()
      this.queryOptionsMap()
    },
    methods: {
      // 查询仓库列表
      async getStoreList() {
        const res = await queryStoreListByReType({ reType: 0 })
        if (res.status === 200) {
          this.storeList = res.data
        }
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.date && this.date.length > 0) {
          query[`${this.dateType}`] = moment(this.date[0]).format()
          query[`${this.dateType}End`] = moment(this.date[1]).format()
          query[`startTime`] = moment(this.date[0]).format()
          query[`endTime`] = moment(this.date[1]).format()
        }
        query[this.csmType] = this.csmText
        if (!this.query.billStatus) query.billStatus = 0
        const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
        if (diff > 93) {
          this.$message.warning('查询时间不得超过三个月')
          return
        }
        query.billType = 13 // 领瓶
        const { status, data } = await queryReceiveBottleList(query)
        if (status === 200) {
          this.tableData.data = data.rows
          if (currentPage === 1) this.tableData.total = data.total

          if (data.footer.length && data.footer[0]) {
            this.receiveSum = data.footer[0].totalNum
          }
        }
      },
      // 查询枚举
      async queryOptionsMap() {
        const res = await mergeAsyncFunc(queryMap, {
          enumName: 'InvenClinerProcessStatus'
        })
        this.bottleStatusMap = res.data // 钢瓶流转管控状态
      },
      // 确认
      async confirm(row) {
        const params = {
          billCode: row.invenBillCode
        }
        const { status } = await receiveBottleAudit(params)
        if (status === 200) {
          this.$notify({
            title: '提示',
            message: `确认成功`,
            type: 'success',
            duration: 2000
          })
          this.search()
        }
      },
      async invalid(row, index) {
        const params = {
          billCode: row.invenBillCode
        }
        const { status } = await receiveBottleInvalid(params)
        if (status === 200) {
          this.$notify({
            title: '提示',
            message: `作废成功`,
            type: 'success',
            duration: 2000
          })
          this.search()
        }
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      reset() {
        this.$refs.form.resetFields()
      },
      detali(row) {
        this.$refs['DetailDialogRef'].show(1, row)
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: flex-end;
}
</style>
